/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: ContractController
 * Author:   Administrator
 * Date:     2020/3/9 15:23
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.h3bpm.web.controller;

import OThinker.Common.Data.BoolMatchValue;
import OThinker.Common.Data.Database.Parameter;
import OThinker.Common.Data.DbType;
import OThinker.Common.Organization.Interface.IOrganization;
import OThinker.Common.Organization.Models.OrganizationUnit;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.Common.Organization.enums.State;
import OThinker.Common.Organization.enums.UnitType;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.RestfulApi.cloudpivot.ResponseResult;
import OThinker.H3.Entity.Data.Attachment.Attachment;
import OThinker.H3.Entity.Data.Attachment.AttachmentHeader;
import OThinker.H3.Entity.Data.DataLogicType;
import OThinker.H3.Entity.Instance.Data.IInstanceDataItem;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Instance.IToken;
import OThinker.H3.Entity.Instance.InstanceContext;
import OThinker.H3.Entity.Instance.TokenState;
import OThinker.H3.Entity.WorkItem.WorkItemModels.WorkItem;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.base.user.UserValidator;
import com.h3bpm.web.qjcEnum.ContractStatusEnum;
import com.h3bpm.web.service.ContractService;
import data.DataException;
import data.DataRow;
import data.DataRowCollection;
import data.DataTable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author Administrator
 * @create 2020/3/9
 * @since 1.0.0
 */
@RequestMapping("/api/contract")
@RestController

public class ContractController extends ControllerBase  {

    private static final Logger logger = LoggerFactory.getLogger(ContractController.class);
    @Autowired
    private ContractService contractService;

    /**
     *  获取流程盖章任务
     * @param instanceId
     * @return
     */
    @RequestMapping("getSignatureWork")
    public ResponseResult getSignatureWork(String instanceId, HttpServletResponse response){
        ResponseResult rst = new ResponseResult(-1L,"",null);
        try {
            logger.info("开始获取代办任务id, instanceId = {}",instanceId);
            String SignatureWorkCode = "Activity47";
            String redirectUrl =  "/Portal/index.html";

            if (super.getUserValidator() != null) {

                InstanceContext instanceContext = getEngine().getInstanceManager().GetInstanceContext(instanceId);


                if (instanceContext == null) {

                    rst.setErrmsg("流程不存在");
                    return  rst;
                }

                IToken aa = instanceContext.GetLastToken(SignatureWorkCode);

                if (aa == null) {
                    // 用印审核未开始
                    redirectUrl = "/Portal/InstanceSheets.html?InstanceId="+instanceId ;
                    response.sendRedirect(redirectUrl);
                    rst.setErrcode(0L);
                }else{
                String[] participants = aa.getParticipants();
                String participant  = "";
                if (participants.length == 0){
                    participant =  User.AdministratorID;
                }else {
                    participant =  participants[0];
                }


                //是 本人,并且是在任务运行中
                if (super.getUserValidator().getUserID().equals(participant) && aa.getState() == TokenState.Running){

                    String sql = "SELECT objectId from ot_workitem WHERE WorkflowCode=? and ActivityCode = ? and InstanceId = ? and Participant = ? ";

                    Parameter[] params = new Parameter[4];


                    params[0]=new Parameter(WorkItem.PropertyName_WorkflowCode, DbType.String,instanceContext.getBizObjectSchemaCode());
                    params[1]=new Parameter(WorkItem.PropertyName_ActivityCode, DbType.String,aa.getActivity());
                    params[2]=new Parameter(WorkItem.PropertyName_InstanceId, DbType.String,instanceId);
                    params[3]=new Parameter(WorkItem.PropertyName_ParticipantName, DbType.String,participant);

                    DataTable workItem = getEngine().getPortalQuery().QueryTable(sql, params);


                    DataRowCollection rows = workItem.getRows();

                    if (rows.size() > 0) {
                        DataRow dataRow = rows.get(0);

                        redirectUrl = "/Portal/WorkItemSheets.html?WorkItemID="+dataRow.getString("objectId") ;

                        response.sendRedirect(redirectUrl);
                        rst.setErrcode(0L);
                        logger.info("获取到代办任务,rows.size = {}",rows.size());
                    } else{
                        rst.setErrmsg("未获取到代办任务");
                        logger.info("未获取到代办任务");
                    }


                }else{
                    redirectUrl = "/Portal/InstanceSheets.html?InstanceId="+instanceId ;
                    response.sendRedirect(redirectUrl);
                    rst.setErrcode(0L);
                }
                }


            }else{
                rst.setErrmsg("未登陆");
                return  rst;
            }



        } catch (Exception e) {
            e.printStackTrace();
            rst.setErrmsg("系统异常");
        }

        return  rst;
    }

    /**
     *
     * @param objectId
     * @param status 当前值,
     * @return
     */
    @RequestMapping("counterpartyUpdateStatusById")
    public ResponseResult counterpartyUpdateStatusById (String objectId,String status){
        ResponseResult rst = new ResponseResult(-1L,"",null);

        logger.info("开始执行相对方状态修改, objectId = {},status = {}",objectId,status);

        if (StringUtils.isBlank(objectId) || StringUtils.isBlank(status)) {
            logger.info("执行相对方状态修改, 数据无效");
            rst.setErrmsg("修改失败");
            return rst;
        }


        if ("禁用".equals(status)) {
            status = "启用";
        } else if ("启用".equals(status)) {
            status = "禁用";
        } else {
            logger.info("执行相对方状态修改, status 参数无效 value = {}",status);
            rst.setErrmsg("修改失败");
            return rst;
        }

        String sql = "update i_counterparty set status = ? WHERE ObjectID = ?";

        Parameter[] params = new Parameter[2];
        params[0]=new Parameter( "status", DbType.String,status);
        params[1]=new Parameter("ObjectID", DbType.String,objectId);

        int i = getEngine().getPortalQuery().ExcuteNoQuery(sql,params);

        if (i>0){
            logger.info("执行相对方状态修改, 修改成功");
            rst.setErrmsg("修改成");
            rst.setErrcode(0L);
        }else {
            logger.info("执行相对方状态修改, 修改失败");
            rst.setErrmsg("修改失败");

        }
        return rst;
    }






    /**
     * 获取当前组织的顶级部门,
     * @param deptId
     * @param rootUnit
     * @return
     */
    private Unit getRootDept(String deptId, OrganizationUnit rootUnit) throws Exception {


        if (rootUnit.getObjectID().equals(deptId)) {
            return  rootUnit;
        }


        Unit unit = getEngine().getOrganization().GetUnit(deptId);

        if (unit != null) {

            if ( rootUnit.getObjectID().equals(unit.getParentID())) {
                return unit;
            }else {
              return  getRootDept(unit.getParentID(), rootUnit);
            }

        }else{

            logger.info("获取部门失败,deptId = {}",deptId);

            return null;
        }

    }


    /**
     * 合同编码生成
     * @param instanceId
     * @return
     */
    @RequestMapping("contractCodeGenerate")
    public ResponseResult contractCodeGenerate(String instanceId){

        return  contractService.contractCodeGenerate(instanceId, getUserValidator().getUserID());
    }

    /**
     * 修改合同状态为终结状态
     * @param objectId
     * @return
     */
//    @RequestMapping("statusToTermination")
//    public ResponseResult updateContractStatusToTermination(String objectId){
//        ResponseResult rst = new ResponseResult(-1L, "", null);
//        boolean bool = contractService.updateContractStatusToTermination(objectId);
//        if (bool) {
//            rst.setErrmsg("执行成功");
//            rst.setErrcode(0L);
//            logger.info("修改合同状态为终结解除合同，执行成功");
//        } else {
//            rst.setErrmsg("执行失败");
//            logger.info("修改合同状态为终结解除合同，执行失败");
//        }
//        return rst;
//
//    }


    /**
     * 修改所有原始合同号相同的合同状态为合同终结（履行完毕）
     * @param contractNum
     * @param rejectEnd
     * @return
     */
    @RequestMapping("statusToFulfilled")
    public ResponseResult updateContractStatusToFulfilled(String contractNum, String rejectEnd) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        logger.info("以合同号 ：{} 为原合同的，执行返回履行中： {}", contractNum, rejectEnd);
        //如果是不是否则不做处理
        boolean bool = contractService.updateContractStatusToFulfilled(contractNum);
        if (bool) {
            rst.setErrcode(0L);
            rst.setErrmsg("执行成功");
            return rst;
        }
        rst.setErrmsg("执行失败");
        return rst;
    }

    /**
     * 修改单个的合同状态为合同终结（履行完毕）
     * @param instanceId
     * @return
     */
    @RequestMapping("oneStatusToFulfilled")
    public ResponseResult oneStatusToFulfilled(String instanceId) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        //如果是不是否则不做处理
        boolean bool = contractService.updateOneContractStatusToFulfilled(instanceId);
        if (bool) {
            rst.setErrcode(0L);
            rst.setErrmsg("执行成功");
            return rst;
        }
        rst.setErrmsg("执行失败");
        return rst;
    }

    /**
     * 获取签订时参与会签的人
     * @param instanceId
     * @return
     */
    @RequestMapping("getCountersignedStaff")
    public ResponseResult getCountersignedStaff(String instanceId){
        ResponseResult rst = new ResponseResult(-1L,"",null);
        Map<String, Object> map = new HashMap<>(1);
        Object countersignedStaff = contractService.getCountersignedStaff(instanceId);
        if (countersignedStaff!=null){
            map.put("countersignedStaff", countersignedStaff);
            rst.setData(map);
            rst.setErrmsg("执行成功");
            rst.setErrcode(0L);
        }else {
            rst.setErrmsg("执行失败");
        }
        return rst;
    }

    /**
     * 更新合同为已归档
     * @param objectId
     * @return
     */
    @RequestMapping("updateContractToArchive")
    public ResponseResult updateContractToArchive(String objectId){
        ResponseResult rst = new ResponseResult(-1L, "", null);
        boolean bool = contractService.updateContractToArchive(objectId);
        if (bool) {
            logger.info("执行合同纸质归档, 修改成功");
            rst.setErrmsg("成功");
            rst.setErrcode(0L);
        } else {
            logger.info("执行合同纸质归档, 修改失败");
            rst.setErrmsg("修改失败");
        }
        return rst;
    }

    /**
     * 修改合同模板的状态
     * @param instanceId
     * @param status
     * @return
     */
    @RequestMapping("updateContractTemplateStatus")
    public ResponseResult updateContractTemplateStatus(String instanceId, String status) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        if (StringUtils.isBlank(instanceId) || StringUtils.isBlank(status)) {
            logger.info("执行合同模板状态修改, 数据无效");
            rst.setErrmsg("修改失败");
            return rst;
        }
        boolean bool = contractService.updateContractTemplateStatus(instanceId, status);
        if (bool) {
            logger.info("执行合同模板状态修改, 修改成功");
            rst.setErrmsg("成功");
            rst.setErrcode(0L);
        } else {
            logger.info("执行合同模板状态修改, 修改失败");
            rst.setErrmsg("修改失败");
        }
        return rst;
    }


    /***
     * 更新流程状态为开始
     * @param objectId
     * @return
     */
    @RequestMapping("updateWorkflowStatusToBegin")
    public ResponseResult updateWorkflowStatusToBegin(String objectId){
        ResponseResult rst = new ResponseResult(-1L, "", null);
        if (StringUtils.isBlank(objectId)) {
            logger.info("执行流程状态修改为流程开始, 数据无效,objectId: {}",objectId);
            rst.setErrmsg("修改失败");
            return rst;
        }
        boolean bool = contractService.updateWorkflowStatusToBegin(objectId);
        if (bool){
            rst.setErrmsg("修改成功");
            rst.setErrcode(0L);
            logger.info("执行流程状态修改为流程开始, 修改成功,objectId: {}",objectId);
        }else {
            rst.setErrmsg("修改失败");
            logger.info("执行流程状态修改为流程开始, 修改失败,objectId: {}",objectId);
        }
        return rst;
    }
    @RequestMapping("updateWorkflowStatusToEnd")
    public ResponseResult updateWorkflowStatusToEnd(String objectId) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        if (StringUtils.isBlank(objectId)) {
            logger.info("执行流程状态修改为流程结束, 数据无效,objectId:  {}",objectId);
            rst.setErrmsg("修改失败");
            return rst;
        }
        boolean bool = contractService.updateWorkflowStatusToEnd(objectId);
        if (bool) {
            rst.setErrmsg("修改成功");
            rst.setErrcode(0L);
            logger.info("执行流程状态修改为流程结束, 修改成功,objectId:  {}",objectId);
        } else {
            rst.setErrmsg("修改失败");
            logger.info("执行流程状态修改为流程结束, 修改失败,objectId:  {}",objectId);
        }
        return rst;
    }




    /**
     * 更新合同状态为中止
     * @param objectId
     * @return
     */
    @RequestMapping("statusToSuspend")
    public ResponseResult updateContractStatusToSuspend(String objectId){
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        boolean bool = contractService.updateContractStatusToSuspend(objectId);
        if (bool){
            responseResult.setErrmsg("成功");
            responseResult.setErrcode(0L);
        }else {
            responseResult.setErrmsg("失败");
        }
        return responseResult;
    }

    /**
     * 变更合同编码规则
     * @param instanceId
     * @return
     */
    @RequestMapping("/contractChangesCodeGenerate")
    public ResponseResult contractChangesCodeGenerate(String instanceId) {
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        if (StringUtils.isBlank(instanceId)) {
            responseResult.setErrmsg("参数有误");
        }
        try {
            boolean bool = contractService.contractChangesCodeGenerate(instanceId);
            if (bool) {
                responseResult.setErrmsg("成功");
                responseResult.setErrcode(0L);
            } else {
                responseResult.setErrmsg("失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            responseResult.setErrmsg(e.getMessage());
        }
        return responseResult;
    }

    /**
     * 解除合同编码规则
     * @param instanceId
     * @return
     */
    @RequestMapping("/contractRelieveCodeGenerate")
    public ResponseResult contractRelieveCodeGenerate(String instanceId) {
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        if (StringUtils.isBlank(instanceId)) {
            responseResult.setErrmsg("参数有误");
        }
        try {
            boolean bool = contractService.contractRelieveCodeGenerate(instanceId);
            if (bool) {
                responseResult.setErrmsg("成功");
                responseResult.setErrcode(0L);
            } else {
                responseResult.setErrmsg("失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            responseResult.setErrmsg(e.getMessage());
        }
        return responseResult;
    }




    /**
     *  获取合同编号
     * @param instanceId
     * @return
     */
    @RequestMapping("/generateContractNumber")
    public ResponseResult generateContractNumber(String instanceId) {
        ResponseResult rst = new ResponseResult(-1L, "", null);

        try {

            UserValidator userValidator = super.getUserValidator();

            if (userValidator != null) {
                //生成合同编码
                rst = contractService.contractCodeGenerate(instanceId, userValidator.getUserID());
            }else {
                rst.setErrmsg("用户未登陆");
            }
        } catch (Exception e) {
            e.printStackTrace();
            rst.setErrmsg("系统异常:"+ e.getMessage());
        }


        return rst;
    }
    /**
     *  获取预览文件
     * @param instanceId
     * @return
     */
    @RequestMapping("getContractPreview")
    public Object getContractPreview(String instanceId,String fileFieldName){
        ResponseResult rst = new ResponseResult(-1L, "", null);

        if (super.getUserValidator() != null) {
            try {
                InstanceData instanceData = new InstanceData(getEngine(), instanceId, super.getUserValidator().getUserID());

                //获取合同文件对象信息
                List<AttachmentHeader> contractFile = instanceData.getBizObject().GetAttachmentHeaders(fileFieldName, BoolMatchValue.True, null);

                Attachment attachment = instanceData.getBizObject().GetAttachment(contractFile.get(0).getAttachmentID());

                Object beExternal = instanceData.getBizObject().GetValue("beExternal");

                if (!"外来合同".equals(beExternal)) {
                    attachment = contractService.fieldReplace(instanceData.getBizObject(), attachment);
                }

                rst.setErrcode(0L);
                rst.setData(attachment.getContent());

            } catch (Exception e) {
                logger.info(e.getMessage(), e);

                rst.setErrmsg("系统异常");
            }

        }else {
            rst.setErrmsg("用户未登陆");
        }

        return  rst.getData();
    }

    /**
     *  生成最终合同
     * @param instanceId s
     * @param attachmentId s
     * @return
     */
    @RequestMapping("generateFinalContract")
    public ResponseResult generateFinalContract(String instanceId,String attachmentId){
        ResponseResult rst = new ResponseResult(-1L, "", null);

        try {
            if (super.getUserValidator() != null) {
                InstanceData instanceData = new InstanceData(getEngine(), instanceId, super.getUserValidator().getUserID());

                Attachment attachment = contractService.generateFinalContract(instanceData, attachmentId);

                Map<String, Object> objMap = new HashMap<>();

                objMap.put("attachmentId", attachment.getAttachmentID());
                objMap.put("bizObjectID", attachment.getBizObjectId());
                objMap.put("schemaCode", attachment.getBizObjectSchemaCode());

                rst.setErrcode(0L);
                rst.setData(objMap);
            }else {
                rst.setErrmsg("用户未登陆");
            }

        } catch (Exception e) {
            rst.setErrmsg("系统异常");
            e.printStackTrace();
            logger.info(e.getMessage(), e);
        }


        return rst;
    }
    /**
     *  根据instanceId 获取合同信息
     * @param instanceId s
     * @return
     */
    @RequestMapping("getContractByInstanceId")
    public ResponseResult getContractByInstanceId(String instanceId) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        try {
            if (super.getUserValidator() != null) {
                Map<String, Object> contractInfo = contractService.getContractByInstanceId(instanceId, super.getUserValidator().getUserID());
                if(contractInfo!=null){
                    rst.setErrcode(0L);
                    rst.setErrmsg("执行成功");
                    rst.setData(contractInfo);
                }else {
                    rst.setErrmsg("执行失败");
                }
            } else {
                rst.setErrmsg("用户未登陆");
            }
        } catch (Exception e) {
            rst.setErrmsg("执行失败");
            e.printStackTrace();
        }
        return rst;
    }

    /**
     *  写入合同主数据
     * @param instanceId
     * @return
     */
    @RequestMapping("insetContractMasterData")
    public ResponseResult insetContractMasterData(String instanceId)  {
        ResponseResult rst = new ResponseResult(-1L,"",null);
        logger.info("合同订立数据写入主数据,instanceId={}", instanceId);

        try {

            if (StringUtils.isNoneBlank(instanceId)) {
                InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

                if (instanceData != null) {
                    String contractNum = (String) instanceData.getBizObject().GetValue("contractNum");

                    if (StringUtils.isNoneBlank(contractNum)){

                        int i = contractService.insetContractMasterData(instanceData);

                        if (i > 0) {
                            rst.setErrcode(0L);
                            logger.info("合同订立写入主数据 成功");
                        } else {
                            logger.info(String.format("合同订立写入主数据 失败 instanceId = {}", instanceId));
                        }

                    }else {
                        rst.setErrmsg("合同号不存在");
                    }
                }else {
                    rst.setErrmsg("合同签订实例不存在");
                }
            }else{
                rst.setErrmsg("参数为null");
            }

        } catch (Exception e) {
            rst.setErrmsg("系统异常:"+e.getMessage());
            logger.info(e.getMessage(), e);
        }
        return  rst;
    }

    /**
     *  用印台账数据写入
     * @param instanceId
     * @return
     */
    @RequestMapping("insetSealRegistrationData")
    public void insetSealRegistrationData(String instanceId){
        logger.info("用印台账数据写入,instanceId={}", instanceId);


        try {

            if (StringUtils.isNoneBlank(instanceId)) {
                InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

                if (instanceData != null) {
                    String stampePass = (String) instanceData.getBizObject().GetValue("stampePass");

                    if ( "用印审核通过".equals(stampePass) ) {

                        // 用印台账 数据
                        int  i = contractService.insetSealRegistrationData(instanceData);

                        if (i > 0) {

                            logger.info(" 用印台账数据写入  成功");
                        } else {
                            logger.info(String.format("用印台账数据写入 失败 instanceId = {}", instanceId));
                        }
                    }
                }
            }


        } catch (Exception e) {
            logger.info(e.getMessage(),e);
            logger.info("系统异常,用印台账数据写入,instanceId={}", instanceId);
        }

    }

    /**
     *  合同状态修改
     */

    @RequestMapping("contractStatusUpdate")
    public void contractStatusUpdate(String instanceId,String status){

        try {

            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

            String stampePass = (String) instanceData.getBizObject().GetValue("stampePass");
            //
            if ( "用印审核不通过".equals(stampePass) ) {
                status = ContractStatusEnum.htzf.getValue();
            }

            contractService.contractStatusUpdate(instanceId,status);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }

    }


    /**
     *  获取合同部门信息
     * @throws Exception
     */
    @RequestMapping("getContractDeptInfo")
    public Object getContractDeptInfo () throws Exception {
        ResponseResult rst = new ResponseResult(-1L,"",null);
        if (super.getUserValidator() == null) {

            rst.setErrmsg("用户未登陆");
            return rst;
        }

        String unitID = super.getUserValidator().getUser().getUnitID();

        IOrganization organization = getEngine().getOrganization();
        //获取所有父级部门id
        List<String> strings = organization.GetParents_Single(unitID, UnitType.OrganizationUnit, true, State.Active);

        String deptList = StringUtils.join(strings,",");

        DataRow dataRow ;
        DataTable dataTable;
        String deptCode=null,dept=null,seal=null,isAppointment=null;

        try {

            // 获取部门编码
            String sql  = "SELECT code,dept from i_deptcodemapping WHERE FIND_IN_SET(dept,'%s') limit 1";

            dataTable = getEngine().getPortalQuery().QueryTable(String.format(sql, deptList));


            if (dataTable.getRows().size() > 0) {
                dataRow = dataTable.getRows().get(0);
                deptCode = dataRow.getString("code");
            }

            // 获取部门使用的章
            sql = "SELECT seal,dept from i_sealusrdept WHERE FIND_IN_SET(dept,'%s') limit 1";

            dataTable = getEngine().getPortalQuery().QueryTable(String.format(sql, deptList));

            if (dataTable.getRows().size() > 0) {
                dataRow = dataTable.getRows().get(0);
                seal = dataRow.getString("seal");
                dept = dataRow.getString("dept");
            }

            // 是否可以预约 合同编号

            sql= "SELECT count(1) from i_appointmentcontractnumber WHERE isTrue = 1 and  FIND_IN_SET(dept,'%s')";
            int count = getEngine().getPortalQuery().count(String.format(sql, deptList));

            if (count > 0) {
                isAppointment = "是";
            }

        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            rst.setErrmsg("系统异常");
            return  rst;
        }


        Map<String, String> map = new HashMap<>();
        map.put("seal", Optional.ofNullable(seal).orElse("1号合同章"));
        map.put("dept", dept);
        map.put("deptCode", Optional.ofNullable(deptCode).orElse("QT"));
        map.put("isAppointment", isAppointment);

        rst.setData(map);
        rst.setErrcode(0L);

        return rst;
    }

    /**
     * 通过原合同编码获取合同文件
     * @param originalContractNum
     */
    @RequestMapping("getContractFile")
    public Object getContractFile(String originalContractNum,String bizObjectId,String bizObjectSchemaCode,String dataField){
        try {
            Object contractFile = contractService.getContractFile(originalContractNum,getUserValidator().getUserID(), bizObjectId, bizObjectSchemaCode, dataField);
            return contractFile;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据部门编码获取部门名称
     * @param unitID
     * @return
     */
    @RequestMapping("getUnitName")
    public Object getUnitName(String unitID){
        ResponseResult rst = new ResponseResult(-1L,"",null);
        try {
            Unit unit = getEngine().getOrganization().GetParentUnitByCategoryCode(unitID,"dept");
//            Unit unit = getEngine().getOrganization().GetUnit(unitID);
            rst.setErrmsg("成功");
            rst.setErrcode(0L);
            rst.setData(unit);
            return rst;
        } catch (Exception e) {
            e.printStackTrace();
            rst.setErrmsg("系统出错");
        }
        return rst;
    }

    /**
     * 根据部门编码获取部门名称
     * @param userID
     * @return
     */
    @RequestMapping("getUserName")
    public Object getUserName(String userID){
        ResponseResult rst = new ResponseResult(-1L,"",null);
        try {
            User user = (User)getEngine().getOrganization().GetUnit(userID);
            rst.setErrmsg("成功");
            rst.setErrcode(0L);
            rst.setData(user.getName());
            return rst;
        } catch (Exception e) {
            e.printStackTrace();
            rst.setErrmsg("系统出错");
        }
        return rst;
    }

    /**
     * 合同变更及合同解除协议插入合同章
     * @param instanceId
     * @return
     */
    @RequestMapping("insertChangesContractData")
    public ResponseResult insertChangesContractData(String instanceId) {
        long startTime=System.currentTimeMillis();
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        logger.info("合同变更(解除协议)开始插入合同主数据,instanceId={}", instanceId);
        if (StringUtils.isBlank(instanceId)) {
            logger.info("合同变更(解除协议)插入合同主数据instanceId不存在");
            responseResult.setErrmsg("参数有误");
            return responseResult;
        }
        try {

            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            if (instanceData != null) {
                String contractNum = (String) instanceData.getBizObject().GetValue("contractNum");

                if (StringUtils.isNoneBlank(contractNum)) {
                    boolean bool = contractService.insertChangesContractData(instanceData);
                    if (bool) {
                        responseResult.setErrmsg("执行成功");
                        logger.info("合同变更(解除协议)插入合同主数据执行成功,instanceId={}", instanceId);
                        responseResult.setErrcode(0L);
                    } else {
                        logger.info("合同变更(解除协议)插入合同主数据执行失败,instanceId={}", instanceId);
                        responseResult.setErrmsg("执行失败");
                    }
                } else {
                    responseResult.setErrmsg("合同变更编号数据不存在");
                    logger.info("合同变更(解除协议)插入合同主数据执行失败,合同变更编号数据不存在,instanceId={}", instanceId);
                }

            } else {
                responseResult.setErrmsg("合同InstanceData数据不存在");
                logger.info("合同变更(解除协议)插入合同主数据执行失败,合同InstanceData数据不存在,instanceId={}", instanceId);
            }


        } catch (Exception e) {
            logger.info("合同变更(解除协议)插入合同主数据执行发生错误: {} ,instanceId={}",e.getMessage(), instanceId);
            responseResult.setErrmsg(e.getMessage());
            e.printStackTrace();
        }
        long endTime=System.currentTimeMillis();
        logger.info("合同变更(解除协议)插入合同主数据 耗时 {} 秒",endTime-startTime);
        return responseResult;
    }
    /**
     * 合同变更及合同解除协议插入合同章
     * @param instanceId
     * @return
     */
    @RequestMapping("insertChangesSealData")
    public ResponseResult insertChangesSealData(String instanceId) {
        long startTime=System.currentTimeMillis();
        logger.info("合同变更(解除协议)开始插入用印主数据,instanceId={}", instanceId);
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        if (StringUtils.isBlank(instanceId)) {
            logger.info("合同变更(解除协议)插入用印主数据instanceId不存在");
            responseResult.setErrmsg("参数有误");
            return responseResult;
        }
        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            boolean bool = contractService.insertChangesSealData(instanceData);
            if (bool){
                responseResult.setErrmsg("执行成功");
                logger.info("合同变更(解除协议)插入用印主数据执行成功,instanceId={}", instanceId);
                responseResult.setErrcode(0L);
            }else {
                logger.info("合同变更(解除协议)插入用印主数据执行失败,instanceId={}", instanceId);
                responseResult.setErrmsg("执行失败");
            }
        } catch (Exception e) {
            logger.info("合同变更(解除协议)插入用印主数据执行发生错误: {} ,instanceId={}",e.getMessage(), instanceId);
            e.printStackTrace();
            responseResult.setErrmsg(e.getMessage());
        }
        long endTime=System.currentTimeMillis();
        logger.info("合同变更(解除协议)插入用印主数据 耗时 {} 秒",endTime-startTime);
        return responseResult;
    }

    /**
     * 变更合同状态为执行中
     * @param instanceId
     * @return
     */
    @RequestMapping("changesStatusToExecuting")
    public ResponseResult statusToExecuting(String instanceId,String makeInstId) {
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        logger.info("两个instId,第一个,本流程的instanceId= " + instanceId);
        logger.info("两个instId,第一个,原流程的instanceId= " + makeInstId);
        boolean bool1 = contractService.updateContractStatusToExecuting(instanceId);
        boolean bool2 = contractService.updateContractStatusToExecuting(makeInstId);
        if (bool1&&bool2){
            responseResult.setErrmsg("执行成功");
            logger.info("更改变更合同与原合同状态为执行中，执行成功");
            responseResult.setErrcode(0L);
        }else {
            responseResult.setErrmsg("执行失败");
        }
        return responseResult;
    }

    @RequestMapping("changesStatusToTermination")
    public ResponseResult StatusToTermination(String instanceId,String makeInstId) {
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        logger.info("两个instId,第一个,本流程的instanceId= " + instanceId);
        logger.info("两个instId,第一个,原流程的instanceId= " + makeInstId);
        boolean bool1 = contractService.updateContractStatusToTermination(makeInstId);
        boolean bool2 = contractService.updateOneContractStatusToFulfilled(instanceId);
        if (bool1&&bool2){
            responseResult.setErrmsg("执行成功");
            logger.info("更改终结合同与原合同状态为终结，执行成功");
            responseResult.setErrcode(0L);
        }else {
            responseResult.setErrmsg("执行失败");
        }
        return responseResult;
    }

    /**
     * 修改合同为已变更
     * @param instanceId
     * @return
     */
    @RequestMapping("updateContractChangesInfo")
    public ResponseResult updateContractChangesInfo(String instanceId) {
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        boolean bool = contractService.updateContractChangesInfo(instanceId);
        if (bool){
            responseResult.setErrmsg("执行成功");
            responseResult.setErrcode(0L);
        }else {
            responseResult.setErrmsg("执行失败");
        }
        return responseResult;
    }

    /**
     * 修改合同为作废
     * @param instanceId
     * @return
     */
    @RequestMapping("statusToNullify")
    public ResponseResult updateContractStatusToNullify(String instanceId) {
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        boolean bool = contractService.updateContractStatusToNullify(instanceId);
        if (bool){
            responseResult.setErrmsg("执行成功");
            responseResult.setErrcode(0L);
        }else {
            responseResult.setErrmsg("执行失败");
        }
        return responseResult;
    }

    /**
     * 获取当前登录用户部门名称
     * @param
     * @return
     */
    @RequestMapping("getLoginUser")
    public Object getUserName(){
        ResponseResult rst = new ResponseResult(-1L,"",null);
        try {
            String unitID = super.getUserValidator().getUser().getUnitID();
            Unit unit = getEngine().getOrganization().GetParentUnitByCategoryCode(unitID,"dept");
//            Unit unit = getEngine().getOrganization().GetUnit(unitID);
            rst.setErrmsg("成功");
            rst.setErrcode(0L);
            rst.setData(unit.getName());
            return rst;
        } catch (Exception e) {
            e.printStackTrace();
            rst.setErrmsg("系统出错");
        }
        return rst;
    }

    /**
     *
     * @param contractNum
     * @param timeOfPerformance
     * @param totalActualPayment
     * @return
     */
    @RequestMapping("updatePerform")
    public ResponseResult updatePerform(String contractNum,String timeOfPerformance,String totalActualPayment) {
        ResponseResult responseResult = new ResponseResult(-1L, "", null);
        boolean bool = contractService.updatePerform(contractNum,timeOfPerformance,totalActualPayment);
        if (bool){
            responseResult.setErrmsg("执行成功");
            responseResult.setErrcode(0L);
        }else {
            responseResult.setErrmsg("执行失败");
        }
        return responseResult;
    }
    @Override
    public String getFunctionCode() {
        return null;
    }

    @Scheduled(cron = "0 10 0 * * ?")
    public void sFkEarly1(){
        logger.info("开始执行检查合同履约定时任务");
        // 检查
        try {
            String sql = "insert into  early_warning (id,usrId,remark,isRead)\n" +
                    "SELECT instId,CreatedBy,concat('您与',secondPartyName,'的',secondSignatory,'签订的编号为:',contractNum,'的',contractName,'合同,将于',DATE_FORMAT(endDate,'%Y年%m月%d日'),'结束距离结束时间还剩7日,请及时处理',if(expensesOrReceipts='收入','收款','付款')), 0  from i_contractdata WHERE DATEDIFF(endDate , now()) =7";

            int i = getEngine().getPortalQuery().ExcuteNoQuery(sql);
            logger.info("定时任务执行检查合同履约成功： {}  个",i);
        } catch (Exception e) {
            logger.info(e.getMessage(),e);
        }

    }

    @Scheduled(cron = "0 0 1 ? * *")
    public void sFkEarly2(){
        logger.info("开始执行检查合同已超期定时任务");
        // 检查
        try {
            String updateSql ="UPDATE i_contractdata set Overdue='是' WHERE Overdue ='否' and contractStatus ='履行中' and unix_timestamp( endDate ) < unix_timestamp( NOW( ) )";
            int i = getEngine().getPortalQuery().ExcuteNoQuery(updateSql);
            logger.info("定时任务执行检查合同已超期成功： {}  个",i);
        } catch (Exception e) {
            logger.info(e.getMessage(),e);
        }

    }


}